package com.wbao.dianniu.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.adapter.JoinActAccountAdapter;
import com.wbao.dianniu.data.ActivityDetailData;
import com.wbao.dianniu.data.ActivityInfos;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.listener.IActivityDetailListener;
import com.wbao.dianniu.listener.IJoinActivityListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.manager.ActivityDetailManager;
import com.wbao.dianniu.update.ActivitySignupManager;
import com.wbao.dianniu.manager.JoinActivityManager;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReportType;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 活动详情
 *
 * @author yejianjun
 */
public class ActivityDetail extends BaseActivity implements IActivityDetailListener, IJoinActivityListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;
    private ImageView headIV;
    private TextView userNameTV;
    private TextView labelTV;
    private ImageView sexIV;
    private ImageView addV;
    private LinearLayout headLayout;
    private TextView subjectTV;
    private TextView maxPersionTV;
    private TextView startDateTV;
    private TextView priceTV;
    private TextView addressTV;
    private TextView browseCountTV;
    private TextView inCountTV;
    private TextView passCountTV;
    private TextView contentTV;
    private TextView reportTV;
    private ListView joinListView;
    private Button talkBtn;
    private Button signUpBtn;
    private Button rightBtn;
    private LinearLayout locationLayout;
    private ActivityDetailManager manager;
    private JoinActivityManager joinManager;
    private int activityId;
    private ActivityDetailData detailData;
    private JoinActAccountAdapter adapter;
    private ScrollView srcollView;
    private LatLng latLng;
    private int inCount;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_detail, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setTitleName("活动详情");
        initWattingView();
        initView();
//		initWattingView();
        initData();
        manager = new ActivityDetailManager(this);
        manager.addActDetailListener(this);
        joinManager = new JoinActivityManager(this);
        joinManager.addJoinActivityListener(this);

        Intent intent = getIntent();
        String id = intent.getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            activityId = Integer.valueOf(id);
        } else {
            activityId = intent.getIntExtra(Const.INTENT_ACTIVITYID, 0);
        }
        requestData(GlobalContext.getAccountId(), activityId);
    }

    private void initWattingView() {
        waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
        waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
        waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
    }

    private void initData() {
        latLng = new LatLng(0, 0);
        adapter = new JoinActAccountAdapter(this);
        List<ActivityInfos> infos = new ArrayList<>();
        adapter.setData(infos);
        joinListView.setAdapter(adapter);
    }

    private void initView() {
        headIV = (ImageView) findViewById(R.id.user_head);
        userNameTV = (TextView) findViewById(R.id.user_name);
        labelTV = (TextView) findViewById(R.id.user_label);
        sexIV = (ImageView) findViewById(R.id.user_sex);
        addV = (ImageView) findViewById(R.id.add_v_iv);
        headLayout = (LinearLayout) findViewById(R.id.user_head_layout);
        subjectTV = (TextView) findViewById(R.id.act_detail_subject);
        maxPersionTV = (TextView) findViewById(R.id.act_detail_maxPersion);
        startDateTV = (TextView) findViewById(R.id.act_detail_startDate);
        priceTV = (TextView) findViewById(R.id.act_detail_price);
        addressTV = (TextView) findViewById(R.id.act_detail_address);
        browseCountTV = (TextView) findViewById(R.id.act_detail_browseCount);
        inCountTV = (TextView) findViewById(R.id.act_detail_inCount);
        passCountTV = (TextView) findViewById(R.id.act_detail_passCount);
        contentTV = (TextView) findViewById(R.id.act_detail_content);
        reportTV = (TextView) findViewById(R.id.act_detail_report);
        joinListView = (ListView) findViewById(R.id.detail_join_listview);
        talkBtn = (Button) findViewById(R.id.detail_online_talk);
        signUpBtn = (Button) findViewById(R.id.detail_to_sign_up);
        locationLayout = (LinearLayout) findViewById(R.id.act_location_layout);
        srcollView = (ScrollView) findViewById(R.id.detail_scrowllview);
        srcollView.smoothScrollTo(0, 0);
        reportTV.setOnClickListener(this);
        talkBtn.setOnClickListener(this);
        signUpBtn.setOnClickListener(this);
        locationLayout.setOnClickListener(this);
//		headIV.setOnClickListener(this);
//		userNameTV.setOnClickListener(this);
//		labelTV.setOnClickListener(this);
        headLayout.setOnClickListener(this);

        rightBtn = getRightTextButton();
        rightBtn.setText(getResources().getString(R.string.share));
        rightBtn.setOnClickListener(this);

    }

    private void requestData(int accountId, int activityId) {
        manager.reqDetail(accountId, activityId);
    }

    @Override
    public void onActDetailFailure(int errorCode, String errorMsg) {
        waittingLayout.setVisibility(View.VISIBLE);
        waittingProBar.setVisibility(View.GONE);
        waittingTV.setText("加载失败，请稍后再试...");
//		ErrorMsgHandler.getInstance().onErrorMsg(this, errorCode, errorMsg);
    }

    @Override
    public void onActDetailSuccess(ActivityDetailData objdata) {
        waittingLayout.setVisibility(View.GONE);
        if (null != objdata) {
            display(objdata);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_head:
            case R.id.user_name:
            case R.id.user_label:
            case R.id.user_head_layout:
                Utils.intoHeadInfoActivity(detailData.info.accountId, ActivityDetail.this);
                break;
            case R.id.act_detail_report://举报
                Utils.intoReportActivity(this, ReportType.TYPE_ACT, activityId);
                break;
            case R.id.detail_online_talk: // 在线咨询
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }
                //跳转到聊天界面
                String appkey = getResources().getString(R.string.app_key);
                GlobalUserData userData = new GlobalUserData();
                LoginSampleHelper.getInstance().openChat(this, userData.getEnvironemt() + detailData.info.accountId, appkey);
                break;
            case R.id.detail_to_sign_up:    //我要报名
                if (!GlobalContext.getPerfectData()) {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                    return;
                }
                joinManager.joinActivity(GlobalContext.getAccountId(), activityId);
                break;
            case R.id.right_button:    // 分享
                // 调用分享内容
                String imageUrl = GlobalContext.cdndownUrl + "logo.png";
                String content = "活动主题：" + detailData.info.subject + "\n" + "活动时间：" + detailData.info.startDate + "\n" + "活动地点：" + detailData.info.address;
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(this, content, 6, imageUrl, detailData.info.id);
                break;
            case R.id.back_button:
                finish();
                break;
            case R.id.act_location_layout:    // 活动地点定位
                Intent mapIntent = new Intent();
                mapIntent.putExtra(Const.INTENT_MAP_LAT, latLng.latitude);
                mapIntent.putExtra(Const.INTENT_MAP_LONG, latLng.longitude);
                mapIntent.setClass(ActivityDetail.this, MapLocActivity.class);
                startActivity(mapIntent);
                break;
            default:
                break;
        }
    }


    @Override
    public void onJoinActivityFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onJoinActivitySuccess() {
        Notification.toast(this, "报名成功，等待通过");
        signUpBtn.setText("等待通过");
        signUpBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
        signUpBtn.setClickable(false);
        inCount++;
        inCountTV.setText("报名：" + inCount);
        ActivitySignupManager.getInstance().signupChaned(activityId, inCount);
    }

    private void display(ActivityDetailData data) {
        double lat = Double.valueOf(data.info.latitude);
        double lon = Double.valueOf(data.info.longitude);
        latLng = new LatLng(lat, lon);
        detailData = data;
        PictureDownloadUtils.displayHeadImage(this, headIV, data.info.headPic);
        userNameTV.setText(data.info.realName);
        labelTV.setText(data.info.label);
        Utils.showSex(this, data.info.userInfo.sex, sexIV);
        Utils.showAuth(data.info.userInfo, addV);
        subjectTV.setText(data.info.subject);
        maxPersionTV.setText(data.info.maxPersion + "人");
        startDateTV.setText(data.info.startDate);
        priceTV.setText(data.info.price + "元/人");
        addressTV.setText(data.info.address);
        browseCountTV.setText("浏览：" + data.info.browseCount);
        inCount = data.info.inCount;
        inCountTV.setText("报名：" + data.info.inCount);
        passCountTV.setText("通过：" + data.info.passCount);
        contentTV.setText(data.info.content);

        if (Utils.IsActivityStart(data.info.startDate)) {
            signUpBtn.setText("已结束");
            signUpBtn.setClickable(false);
        } else {
            if (0 == data.info.inStatus) {
                signUpBtn.setText("我要报名");
                signUpBtn.setClickable(true);
            } else if (1 == data.info.inStatus) {
                signUpBtn.setText("等待通过");
                signUpBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
                signUpBtn.setClickable(false);
            } else if (2 == data.info.inStatus) {
                signUpBtn.setText("已报名");
                signUpBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
                signUpBtn.setClickable(false);
            } else if (3 == data.info.inStatus) {
                signUpBtn.setText(getResources().getString(R.string.already_refused));
                signUpBtn.setBackgroundColor(getResources().getColor(R.color.remark_gray_bg));
                signUpBtn.setClickable(false);
            }
        }

        if (0 == data.joins.size()) {
            adapter.setData(data.joins);
        } else {
            int height = data.joins.size() * Utils.dip2px(this, 50);
            LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, height);
            joinListView.setLayoutParams(lp);
            adapter.setData(data.joins);
            joinListView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeActDetailListener(this);
        }
        if (null != joinManager) {
            joinManager.removeJoinActivityListener(this);
        }
    }
}
